package com.example.comsumer;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author 吕一明
 * @公众号 码客在线
 */
@RestController
public class UserController {

    Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    ProducterClient producterClient;

    @HystrixCommand(fallbackMethod = "testFallBack", commandProperties = {
            @HystrixProperty(name = "execution.isolation.strategy", value="SEMAPHORE"),// 隔离方式 [THREAD, SEMAPHORE]
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
    })
    @GetMapping("test")
    public String test() {
        logger.info("----------------->test");
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject("http://localhost:8088/order/1", String.class);
        return result;
    }

    public String testFallBack() {
        logger.info("----------------->testFallBack");
        return "testFallBack";
    }

    @GetMapping("test2")
    public String test2() {
        RestTemplate restTemplate = new RestTemplate();

        ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCTER-CLIENT");
        String url = String.format("http://%s:%s/order/2", serviceInstance.getHost(), serviceInstance.getPort());
        System.out.println("-------->" + url);

        String result = restTemplate.getForObject(url, String.class);
        return result;
    }

    @GetMapping("test3")
    public String test3() {
        logger.info("----------------->test3");
        String result = restTemplate.getForObject("http://PRODUCTER-CLIENT/order/1", String.class);
        return result;
    }

    @GetMapping("test4")
    public String test4() {
        String result = producterClient.findById(4L);
        return result;
    }
}
